let puppeteer = require('puppeteer');

let md5 = require('md5')
class Crop {
  constructor() {
    this.page = null
    this.browser = null
  }
  async init() {
    this.browser = await puppeteer.launch({
      headless: true,
      args: ['--no-sandbox']
  });
    // this.browser = await puppeteer.launch();
    this.page = await this.browser.newPage();
    this.page.setViewport({
      width: 337,
      height: 667,
      deviceScaleFactor: 2
    });
    await this.getCrop()
  }
  async getCrop(ctx) {
    if(!ctx) return
    let req = ctx.request
    let fileName = md5(req.url)
    // console.log(req.header.origin)
    // console.log(req.url.splice())
    var url = 'https://'+req.header.host+ '/#/plan'+ req.url.slice(5)
    console.log(url)
    // console.log(url)
    // await this.page.goto(url)
    // let arr = []
    // fs.exists(path.join(__dirname,'../public/images/1.png'), function(exists) {
    //   // console.log(exists)
    //   if(exists){
    //     fs.unlinkSync(path.join(__dirname,'../public/images/1.png'))
    //   }
    // });
    await this.page.goto(url)
    await this.page.waitForSelector('#finish');
    await this.screenshotDOMElement(this.page, "body", './public/img/images/'+fileName+'.png');
    let resimg = '/img/images/'+fileName+'.png'
    ctx.body= { "img": resimg}
    // return fileName
    // console.log(1)
  }

  async screenshotDOMElement(page, selector, path, padding = 0) {
    // 获取dom
    const rect = await page.evaluate(selector => {
      try {
        const element = document.querySelector(selector);

        const {
          x,
          y,
          width,
          height
        } = element.getBoundingClientRect();
        if (width * height != 0) {
          return {
            left: x,
            top: y,
            width,
            height,
            id: element.id
          };
        } else {
          return null;
        }
      } catch (e) {
        return null;
      }
    }, selector);
    // 截图
    console.log(rect)
    return await page.screenshot({
      path: path,
      clip: rect ? {
        x: rect.left - padding,
        y: rect.top - padding,
        width: rect.width + padding * 2,
        height: rect.height + padding * 2
      } : null
    });
  }
}
module.exports = Crop